<?php
/*********************************************************************************
* Filename: league_home.php
* 
* This page is used to present the user with information about their league.  This
* includes the overall league standings, schedules for the league, and the smack
* talk board which allows users to post information back and forth about upcoming 
* games.
*
*
* Author: Phillip Peterson
* Date Created: 09/26/2009
**********************************************************************************/
 
//Start the PHP session is it doesn't exist
if (!isset($_SESSION))
	session_start();
//Check if the team is logged in.  If not, redirect the user
//to the login page.
if (!isset($_SESSION['team_id'])){
	include_once "common.php";
	$path = $g_server . $g_login_page;

	header("Location: $path");
	die();
}
   
//The common.php file contains 
include_once "common.php";

//Store the team id which is stored in the session log
$team_id = $_SESSION['team_id'];

echo "$header_open";
echo "$css_league_home";
echo "$js_league_home";
echo "$header_close";

?>

<?php 
    $query = "SELECT * FROM TEAMS WHERE TEAM_ID = $team_id";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $the_league = $row['LEAGUE_ID'];
    
    $query = "SELECT * FROM LEAGUES WHERE LEAGUE_ID = $the_league";
    $results = do_query($query, $g_db_name, $g_username);
    $row = mysql_fetch_assoc($results);
    $draft_done = $row['DRAFT_DONE'];
    $scheduled = $row['SCHEDULED'];
    
   	//Query to get the current week for the league
	$query = "SELECT WEEK
			  FROM GAMES
			  WHERE ISNULL(TEAM_1_SCORE)";
	$results = do_query($query, $g_db_name, $g_username);    
    
    if (!$draft_done) {
	    $path = $g_server . $g_nodraft_page;
    	header("Location: $path");
    	die();
    }
    else if (!$scheduled) {
        $path = $g_server . $g_noschedule_page;
    	header("Location: $path");
    	die();
    } 
    //Check if the all league games have been played, if so
    //forward the user to the champ page
    else if (mysql_num_rows($results) == 0){
        $path = $g_server . $g_champ;
	    header("Location: $path");
	    die();
    }    
    else {
?>

<body onload="postLoadLeague();">
	<div id="wrapper">
		<div id="inner">
			<?php
				echo "$g_nav_div";
			?>
			<div id="content">
				<div id="container-1">
					<ul class="ui-tabs-nav">
						<li class="ui-tabs-selected">
							<a href="#fragment-1">
								<span>Standings</span>
							</a>
						</li>
						<li class="">
							<a href="#fragment-2">
								<span>Schedule</span>
							</a>
						</li>
					</ul>

					<div id="fragment-1" class="ui-tabs-panel">
						<table>
								<tr class="table_header">
									<td class="rank_cell rank_cell_header">Rank</td>
									<td class="team_cell team_cell_header">Team</td>
									<td class="point_cell point_cell_header">W-L-T</td>
									<td class="point_cell point_cell_header">Pct</td>
									<td class="point_cell point_cell_header">Pts</td>
									<td class="point_cell point_cell_header">Moves</td>
								</tr>
									<?php
                                   		//Select the win-tie-loss information for all of
										//the teams in the league.  This will be used to 
										//calculate the standings.
									    $query = "SELECT * 
                                                  FROM TEAMS 
                                                  WHERE LEAGUE_ID IN 
                                                      (SELECT LEAGUE_ID 
                                                      FROM TEAMS 
                                                      WHERE TEAM_ID=$team_id)
                                                      ORDER BY PCT DESC, POINTS DESC";
										$results = do_query($query, $g_db_name, $g_username);
    
                                        //Get information for each team in the league, so correct
                                        //rankings can be assigned
										while ($row = mysql_fetch_array($results)){
											$team_name[]    = $row['TEAM_NAME'];
											$team_wins[]    = $row['WIN'];
											$team_loss[]    = $row['LOSS'];
											$team_draw[]    = $row['DRAW'];
                                            $team_points[]  = $row['POINTS'];
                                            $team_pct[]     = $row['PCT'];
											$ids[]          = $row['TEAM_ID'];
										}

										$shade = true;
										//Add a new row for every team in the league.  The teams are already
                                        //ordered by their rank from the query above.
										for($i = 0; $i < sizeof($team_name); $i++){
											//Add a new row to the table and fill in the
											//needed cells with each team's information
											$class = ($shade) ? "shade_odd" : "shade_even";
											$shade = !$shade;

											$record = $team_wins[$i] ."-". $team_loss[$i] ."-". $team_draw[$i];
                                            //Format the win percentage to have fixed number of decimal points
                                            $pct = number_format($team_pct[$i],3); 
                                            $rank = $i + 1;
											
											$query = "SELECT COUNT(*) AS NUM
													  FROM PEND_TRADE 
													  WHERE TEAM1 = {$ids[$i]} OR TEAM2 = {$ids[$i]}";
											$result = do_query($query, $g_db_name, $g_username);
											$row = mysql_fetch_assoc($result);
											$num = $row['NUM'];
        
                                            //Add the row to the table
											echo" <tr class=$class>";
											echo"   <td class='rank_cell'>$rank</td>";
											echo"   <td class='team_cell'>{$team_name[$i]}</td>";
											echo"   <td class='point_cell'>$record</td>";
											echo"   <td class='point_cell'>$pct</td>";
											echo"   <td class='point_cell'>{$team_points[$i]}</td>";
											echo"   <td class='point_cell'>$num</td>";
											echo" </tr>";
										}
									?>
							</table>
					</div>
					<div id="fragment-2" class="ui-tabs-panel ui-tabs-hide">
												
						<table class="expandable">
							<tr class="table_header">
								<td width=25></td>
								<td width=100>Week</td>
								<td class="team_cell">Home Team</td>
								<td class="team_cell">Away Team</td>
								<td class="score_cell">Score</td>
							</tr>
							<?php
								// Grab the league ID
								$query = "SELECT LEAGUE_ID FROM TEAMS WHERE TEAM_ID = $team_id";
								$results = do_query($query,$g_db_name,$g_username);
							    $row = mysql_fetch_array($results);
								$league_id = $row['LEAGUE_ID'];

								// Grab each game by week
								$query = "SELECT GAME_ID, WEEK 
								          FROM TEAMS LEFT OUTER JOIN GAMES ON TEAM1 = TEAM_ID 
								          WHERE LEAGUE_ID = $league_id 
								          ORDER BY WEEK asc";
								$results = do_query($query,$g_db_name,$g_username);
								$i = 0;

								while ($row = mysql_fetch_array($results)) {
									$week = $row['WEEK'];
									
									// Create parent row
									if ($i != $week) {
										$shade = (($i+1)%2) ? 'shade_odd' : 'shade_even';										
										$i = $i + 1;
										echo" <tr class=$shade onmouseover='rowHover(this);' onmouseout='rowUnHover(this);'>";
										echo"   <td class='table_arrow'>+</td>";
										echo"   <td>Week $i</td>";
										echo"   <td></td>";
										echo"   <td></td>";
										echo"   <td></td>";
										echo" </tr>";
									}

									$game_id = $row['GAME_ID'];

									$child_query = "SELECT (SELECT TEAM_NAME FROM TEAMS WHERE TEAM_ID = TEAM1) as HOME_TEAM, 
													(SELECT TEAM_NAME FROM TEAMS WHERE TEAM_ID = TEAM2) as AWAY_TEAM, TEAM_1_SCORE,
                                                    TEAM_2_SCORE, WEEK
													FROM GAMES WHERE GAME_ID = $game_id AND WEEK = $i";
									$child_result = do_query($child_query,$g_db_name,$g_username);

									// Cycle through every week and grab the associated games scheduled for that week
                                    if ($child_result) {
									    while ($child_row = mysql_fetch_assoc($child_result)) {
										    $home_team  = $child_row['HOME_TEAM'];
										    $away_team  = $child_row['AWAY_TEAM'];
										    $home_score = $child_row['TEAM_1_SCORE'];
										    $away_score = $child_row['TEAM_2_SCORE'];
                                            $week       = $child_row['WEEK'];
										    $home_mod = "";
										    $away_mod = "";
										    $middle_mod = "-";
									
										    // Display winnner and lower legend
										    if ($home_score > $away_score) {
											    $home_mod = "<b>(W)</b>";
											    $away_mod = "(L)";
										    } else {
											    $home_mod = "(L)";
											    $away_mod = "<b>(W)</b>";
										    }
									
										    // If the game hasn't been played, TDB legend
										    // is dispayed.
										    if ($home_score == 0 && $away_score == 0) {
											    $middle_mod = "Week $week";
											    $home_mod = "";
											    $away_mod = "";
										    }

										    echo "<tr class=$shade>
												    <td></td>
												    <td></td>
												    <td $align>$home_team $home_mod</td>
												    <td $align>$away_team $away_mod</td>
												    <td $align>$home_score $middle_mod $away_score</td>
											     </tr>
										    ";
								        }
                                    }
								} 							
								?>
						</table>

					</div>
				</div>

				<div style="visibility:hidden;">
					<h6>Recent Transactions</h6>
				</div>

				<div id="recent_transactions" class="lh_div_indent">
					<h3>Recent Transactions</h3>
					<table class="lh_table_strech" id="transaction">
						<tr class="table_header">
							<td class="date_cell">Date</td>
							<td class="type_cell">Type</td>
							<td class="details_cell">Details</td>
						</tr>
						
						<?php
						    //Get all of the trades which have occured
						    $query = "SELECT *, UNIX_TIMESTAMP(ACCEPTED_ON) AS THE_DATE
						              FROM PEND_TRADE 
						              WHERE STATUS = 'Accepted' OR STATUS = 'Free Agent'
						              ORDER BY ACCEPTED_ON DESC";
						              
						    $results = do_query($query,$g_db_name,$g_username);
						    
						    while ($row = mysql_fetch_assoc($results)){
						        $team1[]   = get_value("team_id",$row['TEAM1']);
						        $team2[]   = get_value("team_id",$row['TEAM2']);
						        $player1[] = get_value("player_id",$row['PLAYER1']);
						        $player2[] = get_value("player_id",$row['PLAYER2']);
						        $date[]    = date("D. M jS",$row['THE_DATE']);
						        $status[]  = $row['STATUS']; 
						    }
						    
						    $flag = 1;
						    
						    for ($i = 0; $i < sizeof($team1); $i++){
						        $class = ($flag) ? "trans_row_even" : "trans_row_odd";
						        
						        echo "<tr class=$class>";
						        echo "<td>{$date[$i]}</td>";
						        echo "<td>";
						        if ($status[$i] == 'Accepted'){
						            echo"
						                  <img src='images/icons/icon_trade.gif' width='35' height='35'>
						                  <span class='nextImage'>Team-Team Trade</span>
						              </td>
						              <td>
						                  <span class='bold'>{$player1[$i]}</span> from {$team1[$i]} to {$team2[$i]}
						                  <br>
						                  <span class='bold'>{$player2[$i]}</span> from {$team2[$i]} to {$team2[$i]}
						              </td>";						        
						        }
						        else {
						            echo"
						                  <img src='images/icons/icon_adddrop.gif' width='35' height='35'>
						                  <span class='nextImage'>Add/Drop</span>
						              </td>
						              <td>
						                  <span class='bold'>{$player2[$i]}</span> added from waivers to {$team1[$i]}
						                  <br>
						                  <span class='bold'>{$player1[$i]}</span> dropped from {$team1[$i]} to waivers
						              </td>";
						        }
						        echo "</tr>";
						        $flag = !$flag;
						   }
						   ?>	
					</table>
					<?php
                        //Check if more than 5 results exist
    				    echo "<div id='view_all_trans'>";
    				    echo "<p onclick='showAllTrans(this);'>View All</p>";
    				    echo "</div>";
    			    ?>
				</div>
				
				
				<div id="recent_messages" class="lh_div_indent">
					<h3>Recent Messages</h3>
					<div id="mess_contain">
					<table id="message_table" class="lh_table_strech">						
					    <tr id="no_row" class="table_header">
							<td class="point_cell">a</td>
						</tr>

						<?php
						
    						//Query to get the list of messages
    						$query = "SELECT UNIX_TIMESTAMP(DATE) AS THE_DATE,MESG,SMACKBOARD.TEAM_ID AS THE_TEAM_ID 
    						          FROM SMACKBOARD 
    						          LEFT JOIN TEAMS ON SMACKBOARD.TEAM_ID = TEAMS.TEAM_ID 
    						          WHERE LEAGUE_ID = {$_SESSION['league_id']} ORDER BY DATE DESC";
    						          
    						$result = do_query($query,$g_db_name,$g_username);
							
							$num_messages = mysql_num_rows($result);
							echo "<script type='text/javascript'> var g_num_message  = $num_messages;</script>";


    						
    						if (!mysql_num_rows($result)){
    						    echo "<tr>";
    						    echo "<td colspan=4 id='no_message'>No messages from your league.</td>";
    						    echo "</tr>";
    						}
    						else {
							
								$limit = false;
								if (mysql_num_rows($result) > 5){
									$limit = true;
								}
								
    						    $msg        = array();
    						    $subject    = array();
    						    $date       = array();
    						    $time       = array();
    						    $team_names = array();
    						    $team_ids   = array();
    						    
        						while ($row = mysql_fetch_assoc($result)){
        						    $msg[]        = $row['MESG'];
        						    $date[]       = date("m/d",$row['THE_DATE']); 
        						    $time[]       = date("g:i a",$row['THE_DATE']); 
        						    $team_names[] = get_value("team_id",$row['THE_TEAM_ID']);
        						    $team_ids[]   = $row['THE_TEAM_ID'];
        						}
        						
        						$row = "";
        						//Insert a new row for all of the message
        						for ($i = 0; $i < sizeof($team_ids); $i++){
									$visible = ($i < 5) ? 'message_row_show' : 'message_row_hidden';
									$shade = ($i % 2) ? 'message_no_shade' : 'message_shade';
            						$row .= "<tr class='$visible $shade'><td class='rela_row'>";
            						$row .= "<div class='team_message'>";
            						
            						$query  = "SELECT * FROM TEAMS WHERE TEAM_ID = {$team_ids[$i]}";
            						$result = do_query($query,$g_db_name,$g_username);
            						$fetch  = mysql_fetch_assoc($result);
            						$image_id = $fetch['AVATAR'];
            						if ($image_id == NULL) {
            						    $image_id = "default.ico";         						    
            						}
            						    
            						$row .= "   <img class='team_icon' src='images/icons/teams/$image_id'>";
            						$row .= "   <div class='team_message_name'>{$team_names[$i]}</div>";
            						$row .= "   <div class='team_message_time'>{$date[$i]} {$time[$i]}</div>";
            						$row .= "   <div class='team_message_msg'>{$msg[$i]}</div>";
            						$row .= "</div>";
            						$row .= "</td></tr>";
            				    }
            				    echo $row;
        				    }
					
							echo "</table>";
							echo "</div>";
							//Check if more than 5 results exist
							echo "<div id='view_all'>";
							echo "<p onclick='showAll(this);'>View All</p>";
							echo "</div>";
								
        		        ?>
								
					<div id="new_message_box">
					    <textarea id="message_post" onfocus="messageFocus(this);" onblur="messageBlur(this);"
					              rows="2" cols="91">
					    </textarea>
					</div>
					<div>
					    <input id="post_button" type="button" value="Post" onclick="submitMessage(this);">
					</div>
				</div>

			</div><!--Close content-->
			<script type='text/javascript'> var g_team_id  = <?php echo $team_id ?>;</script>

			<div id="sidebar">
                <div id="tropy_guy">
                </div>
			</div>	
			
			<div id="footer">
			  <?php echo "$footer"; ?>
			</div>
		</div>
	</div>
</body>
<?php } ?>
</html>
